// src/composables/useSendCode.ts
import { ref, onUnmounted } from 'vue';

export function useSendCode() {
  const disabled = ref(false);
  const text = ref('获取验证码'); 
  const runTime = ref<number | null>(null);

  const sendCode = () => {
    if (disabled.value) return;
    disabled.value = true;
    let n = 60;
    text.value = '剩余' + n + 's'; 
    runTime.value = window.setInterval(() => {
      n = n - 1;
      if (n < 0) {
        clearInterval(runTime.value!);
        runTime.value = null;
        disabled.value = false;
        text.value = '重新获取'; 
        return;
      }
      text.value = '剩余' + n + 's'; 
    }, 1000);
  };

  // 页面卸载时清除定时器
  onUnmounted(() => {
    if (runTime.value) {
      clearInterval(runTime.value);
      runTime.value = null;
    }
  });

  return {
    disabled,
    text,
    sendCode,
  };
}